package com.lfz.demo.controller;

import com.lfz.demo.entity.PopulationGlobalData;
import com.lfz.demo.service.GlobalService;
import com.lfz.demo.utils.RedisUtil;
import com.lfz.demo.vo.DataView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author lfz
 * @date 2025/2/25 18:16
 */
@RestController
public class GlobalController {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtil.class);
    // 缓存时间常量（单位：分钟）
    private static final int CACHE_EXPIRE = 60; //缓存过期时间（60分钟）。
    private static final String CACHE_PREFIX = "index:"; //缓存键前缀，避免键冲突。


    @Autowired
    private GlobalService globalService;

    @Autowired
    private RedisUtil redisUtil;

    @GetMapping("/queryGlobal")
    public List<PopulationGlobalData> queryGlobalData(){
        PopulationGlobalData populationGlobalData = new PopulationGlobalData();
        String cacheKey = CACHE_PREFIX + String.format("global:list:%s:%s:%d",
                populationGlobalData.getName(),
                populationGlobalData.getValue(),
                populationGlobalData.getYear()
        );

        try {
            List cachedData = (List) redisUtil.get(cacheKey);
            if (cachedData != null) {
                return cachedData;
            }
        } catch (Exception e) {
            logger.error("Redis反序列化失败，降级查询MySQL", e);
        }

        List<PopulationGlobalData> list = globalService.list();

        try {
            redisUtil.set(cacheKey, list, CACHE_EXPIRE); // 缓存60分钟
        } catch (Exception e) {
            logger.error("缓存设置失败，但不影响业务流程", e);
        }
        return list;
    }
}
